import {
  Badge,
  Card,
  Descriptions,
  Divider,
  Table,
  Form,
  Button,
  Input,
  Radio,
  Row,
  Col,
  Select,
  InputNumber,
  Tag,
} from 'antd';
import React, { Component } from 'react';

import { Dispatch } from 'redux';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { connect } from 'dva';
import { BasicProfileDataType } from './data.d';
import EditForm, { FormValsType } from './components/EditForm';
import Certification from './components/Certification';
import Contract from './components/Contract';
import AddForm from './components/AddForm';

import Validator from '@/utils/Validator';
import styles from './style.less';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const R = require('ramda');

interface MyEnterpriseProps {
  loading: boolean;
  dispatch: Dispatch<any>;
  manageEnterpriseMyEnterprise: BasicProfileDataType;
}
interface MyEnterpriseState {
  visible: boolean;
}

//数字常量
const num = {
  ZERO: '0',
  ONE: '1',
  TWO: '2',
  THREE: '3',
  FOUR: '4',
};

// 客户状态
const cstStatus = {
  DELETED: '0', // 删除
  APPLY: '1', //草稿
  APPROVAL: '2', //待审核
  ADDINFO: '3', //待补充资料
  APPROVALSUCCESSED: '4', //审核成功
  APPROVALFAILED: '5', //审核失败
};

//签约状态
const convertCstStatus = status => {
  if (status === cstStatus.APPROVAL || status === cstStatus.ADDINFO) {
    return '签约中';
  }
  if (status === cstStatus.APPROVALSUCCESSED) {
    return '已签约';
  } else if (status === cstStatus.APPLY) {
    return '未签约';
  } else if (status === cstStatus.ADDINFO) {
    return '审核中';
  }
  return '未知';
};

//认证状态
const convertAuthStatus = status => {
  let res = '未知';
  if (status === '1') {
    res = '未认证';
  } else {
    if (status == cstStatus.APPROVAL) {
      res = '洲博通审核中';
    }
    if (status == cstStatus.APPROVALSUCCESSED) {
      res = '认证成功';
    }
    if (status == cstStatus.APPROVALFAILED) {
      res = '认证失败';
    }
  }
  return res;
};

//企业类型
const companyType = companytype => {
  let res = '未知';
  if (companytype === num.ZERO) {
    res = '一般纳税人';
  }
  if (companytype === num.ONE) {
    res = '小规模';
  }
  if (companytype === num.TWO) {
    res = '境外';
  }
  if (companytype === num.THREE) {
    res = '个人';
  }

  return res;
};

//经营模式
const businessModel = businessmodel => {
  let res = '未知';
  if (businessmodel == num.ZERO) {
    res = '工贸一体';
  }
  if (businessmodel == num.ONE) {
    res = '贸易型公司';
  }
  if (businessmodel == num.TWO) {
    res = '生产型工厂';
  }

  return res;
};

//表单数据
let fieldsData = {};

@connect(
  ({
    manageEnterpriseMyEnterprise,
    loading,
  }: {
    manageEnterpriseMyEnterprise: BasicProfileDataType;
    loading: {
      effects: { [key: string]: boolean };
    };
  }) => ({
    manageEnterpriseMyEnterprise,
    loading: loading.effects['manageEnterpriseMyEnterprise/fetchUserInfo'],
  }),
)
class MyEnterprise extends Component<MyEnterpriseProps, MyEnterpriseState> {
  constructor(props) {
    super(props);
    this.initData(props.manageEnterpriseMyEnterprise.userInfo, true);
  }

  componentDidMount() {
    this.handleGetUserInfos();
  }

  componentWillReceiveProps(nextProps) {
    if (
      !R.equals(this.props.manageEnterpriseMyEnterprise.userInfo)(
        nextProps.manageEnterpriseMyEnterprise.userInfo,
      )
    ) {
      this.initData(nextProps.manageEnterpriseMyEnterprise.userInfo);
    }
  }

  initData = (value, flag) => {
    value = R.isNil(value) ? [] : value;
    if (flag) {
      this.state = {
        editStatus: false,
        certificationFlag: false,
        contractFlag: false,
        editFlag: false,
        addFlag: false,
      };
    }
  };

  /**
   * 捕获编辑状态
   *
   * @param status
   */
  handleEditStatus(editStatus: boolean) {
    const { dispatch, manageEnterpriseMyEnterprise } = this.props;
    const { userInfo } = manageEnterpriseMyEnterprise;

    this.setState({
      editStatus,
    });
  }

  handleCancel = () => {
    this.setState({
      editStatus: false,
    });
  };

  handleGetUserInfos = () => {
    const { dispatch, manageEnterpriseMyEnterprise } = this.props;

    dispatch({
      type: 'manageEnterpriseMyEnterprise/fetchUserInfo',
      payload: {
        onSuccess: userInfo => {
          //认证成功的用户可以洲博通签约
          if (R.equals(userInfo.certificationStatus)(cstStatus.APPROVALSUCCESSED)) {
            if (R.equals(userInfo.status)(cstStatus.APPLY)) {
              this.setState({ contractFlag: true });
            } else {
              this.setState({ contractFlag: false });
            }
          } else {
            this.setState({ contractFlag: false });
          }

          if (
            R.isEmpty(userInfo.certificationStatus) ||
            R.isNil(userInfo.certificationStatus) ||
            R.equals(userInfo.certificationStatus)(cstStatus.APPLY) ||
            R.equals(userInfo.certificationStatus)(cstStatus.ADDINFO)
          ) {
            if (R.equals(userInfo.status)(cstStatus.APPLY)) {
              this.setState({ certificationFlag: true });
            } else {
              this.setState({ certificationFlag: false });
            }
          } else {
            this.setState({ certificationFlag: false });
          }

          if (
            R.isEmpty(userInfo) ||
            R.isNil(userInfo) ||
            R.equals(JSON.stringify(userInfo))('{}')
          ) {
            this.setState({ editFlag: false, addFlag: true });
          } else {
            this.setState({ addFlag: false });

            if (
              (R.equals(userInfo.certificationStatus)(cstStatus.APPLY) ||
                R.isEmpty(userInfo.certificationStatus) ||
                R.isNil(userInfo.certificationStatus)) &&
              R.equals(userInfo.status)(cstStatus.APPLY) &&
              userInfo.owner
            ) {
              this.setState({ editFlag: true });
            } else {
              this.setState({ editFlag: false });
            }
          }
        },
      },
    });
  };

  //签约
  handleContract = () => {
    if (this.contract) this.contract.handleOpen();
  };

  //认证
  handleCertification = () => {
    if (this.certification) this.certification.handleOpen();
  };

  //新建
  handleAdd = () => {
    if (this.addForm && this.state.addFlag) this.addForm.handleOpen();
  };

  render() {
    const { manageEnterpriseMyEnterprise, loading, dispatch } = this.props;
    const { editStatus, certificationFlag, contractFlag, editFlag } = this.state;
    const { userInfo } = manageEnterpriseMyEnterprise;

    let contractBtn =
      contractFlag == false ? (
        ''
      ) : (
        <Button
          style={{ marginLeft: 10 }}
          type="primary"
          size="small"
          onClick={() => {
            this.handleContract(true);
          }}
        >
          签约
        </Button>
      );
    let certificationBtn =
      certificationFlag == false ? (
        ''
      ) : (
        <Button
          style={{ marginLeft: 10 }}
          type="primary"
          size="small"
          onClick={() => {
            this.handleCertification(true);
          }}
        >
          认证
        </Button>
      );
    let editBtn =
      editFlag == false ? (
        ''
      ) : (
        <Button
          style={{ marginLeft: 10 }}
          type="primary"
          size="small"
          onClick={() => {
            this.handleEditStatus(true);
          }}
        >
          编辑
        </Button>
      );

    let addBtn =
      this.state.addFlag == true ? (
        <Button
          style={{ marginLeft: 10 }}
          type="primary"
          size="small"
          onClick={() => {
            this.handleAdd(true);
          }}
        >
          新建
        </Button>
      ) : (
        ''
      );
    return (
      <PageHeaderWrapper>
        {editStatus ? (
          <EditForm
            {...this.props.manageEnterpriseMyEnterprise}
            dispatch={dispatch}
            cstStatus={convertCstStatus(userInfo.status)}
            handleCancel={this.handleCancel.bind(this)}
            state={this.state}
            handleGetUserInfos={this.handleGetUserInfos.bind(this)}
            data={userInfo}
          />
        ) : (
          <Card
            bordered={false}
            title={
              <span>
                {userInfo.entepriseName} &nbsp;
                <Tag color="red">
                  {R.equals(JSON.stringify(userInfo))('{}')
                    ? '暂无企业信息'
                    : convertCstStatus(userInfo.status)}
                </Tag>
              </span>
            }
            extra={
              <span>
                {certificationBtn}
                {contractBtn}
                {editBtn}
                {addBtn}
              </span>
            }
          >
            <div>
              <Descriptions title="基本信息" style={{ marginBottom: 32 }}>
                <Descriptions.Item span={12} label="中文名">
                  {editStatus ? <Input /> : userInfo.entepriseName}
                </Descriptions.Item>
                <Descriptions.Item span={12} label="英文名">
                  {userInfo.entepriseNameEn}
                </Descriptions.Item>
                <Descriptions.Item span={12} label="统一信用代码">
                  {userInfo.taxpayerid}
                </Descriptions.Item>
                <Descriptions.Item span={12} label="认证状态">
                  {convertAuthStatus(userInfo.certificationStatus)}
                </Descriptions.Item>
                <Descriptions.Item span={12} label="签约状态">
                  {convertCstStatus(userInfo.status)}
                </Descriptions.Item>
              </Descriptions>

              <Divider style={{ marginBottom: 32 }} />
              <Descriptions title="详细信息" style={{ marginBottom: 32 }}>
                <Descriptions.Item label="客户简称">{userInfo.shortname}</Descriptions.Item>
                <Descriptions.Item label="是否查询企业信用">
                  {R.isEmpty(userInfo) || R.isNil(userInfo)
                    ? ''
                    : userInfo.ischeckinfo === '1'
                    ? '是'
                    : '否'}
                </Descriptions.Item>
                <Descriptions.Item label="企业类型">
                  {R.isEmpty(userInfo) || R.isNil(userInfo)
                    ? ''
                    : companyType(userInfo.companyType)}
                </Descriptions.Item>
                <Descriptions.Item label="经营模式">
                  {R.isEmpty(userInfo) || R.isNil(userInfo)
                    ? ''
                    : businessModel(userInfo.businessmodel)}
                </Descriptions.Item>
                <Descriptions.Item label="移动电话">{userInfo.mobile}</Descriptions.Item>
                <Descriptions.Item label="固定电话">{userInfo.telephone}</Descriptions.Item>
                <Descriptions.Item label="邮箱（email）">{userInfo.email}</Descriptions.Item>
                <Descriptions.Item label="传真">{userInfo.tax}</Descriptions.Item>
                <Descriptions.Item label="海关注册登记号码">
                  {userInfo.customsregno}
                </Descriptions.Item>
                <Descriptions.Item label="公司地址(中文)">{userInfo.address}</Descriptions.Item>
                <Descriptions.Item label="公司地址(英文)">{userInfo.addressen}</Descriptions.Item>
                <Descriptions.Item label="收件地址">{userInfo.recaddress}</Descriptions.Item>
                <Descriptions.Item label="公司网址">{userInfo.url}</Descriptions.Item>
              </Descriptions>
            </div>
          </Card>
        )}
        <Certification
          wrappedComponentRef={inst => (this.certification = inst)}
          dispatch={this.props.dispatch}
          data={userInfo}
          refreshData={this.handleGetUserInfos.bind(this)}
        />

        <Contract
          wrappedComponentRef={inst => (this.contract = inst)}
          dispatch={this.props.dispatch}
          data={userInfo}
          refreshData={this.handleGetUserInfos.bind(this)}
        />

        <AddForm
          wrappedComponentRef={inst => (this.addForm = inst)}
          dispatch={this.props.dispatch}
          data={userInfo}
          refreshData={this.handleGetUserInfos.bind(this)}
        />
      </PageHeaderWrapper>
    );
  }
}

export default MyEnterprise;
